package com.hzy.fivepalace.admin.service;

import com.hzy.fivepalace.admin.dao.AdminToken;
import com.hzy.fivepalace.common.consts.RedisKeyConsts;
import com.hzy.fivepalace.common.service.redis.RedisCache;
import com.hzy.fivepalace.common.util.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * 维护用户token
 */
@Component
public class AdminTokenManager {

	/**
	 * token有效期天数
	 */
	private final static int days =1;

	private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

	@Resource
	private RedisCache redisCache;

	public  Integer getAdminId(String token) {
		AdminToken userToken =redisCache.getCacheObject(token);
		if (userToken == null) {
			return null;
		}
		if (userToken.getExpireTime().isBefore(LocalDateTime.now())) {
			redisCache.deleteObject(token);
			return null;
		} else {
			verifyToken(userToken, token);
		}
		return userToken.getUserId();
	}


	/**
	 * 验证令牌有效期，相差不足20分钟，自动刷新缓存
	 *
	 * @param adminToken
	 * @param token
	 */
	public  void verifyToken(AdminToken adminToken, String token) {
		long expireTime = adminToken.getExpireTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
		long currentTime = System.currentTimeMillis();
		if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
			LocalDateTime update = LocalDateTime.now();
			LocalDateTime expire = update.plusDays(days);
			adminToken.setExpireTime(expire);
			adminToken.setUpdateTime(update);
			redisCache.setCacheObject(token, adminToken);
		}
	}

	public  AdminToken generateToken(Integer id, String sessionId) {
		AdminToken adminToken;
		String token ="admin-token-"+CharUtils.getRandomString(32,id);
		LocalDateTime update = LocalDateTime.now();
		LocalDateTime expire = update.plusDays(days);
		adminToken = new AdminToken();
		adminToken.setSessionId(sessionId);
		adminToken.setToken(token);
		adminToken.setUpdateTime(update);
		adminToken.setExpireTime(expire);
		adminToken.setUserId(id);
		redisCache.setCacheObject(token, adminToken);
		return adminToken;
	}



	public void removeToken(String token) {
		if(!StringUtils.isBlank(token)){
			AdminToken userToken =redisCache.getCacheObject(token);
			if(null!=userToken){
				redisCache.deleteObject(token);
			}
		}
	}
}
